<template>
  <view class="login-container">
    <view class="login-form">
      <u-form :model="form" ref="uForm">
        <u-form-item label="账号" prop="account">
          <u-input
            v-model="form.account"
            placeholder="请输入账号"
            border="bottom"
          ></u-input>
        </u-form-item>
        <u-form-item label="密码" prop="password">
          <u-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            border="bottom"
          ></u-input>
        </u-form-item>
      </u-form>

      <view class="login-btn">
        <u-button type="primary" text="登录" @click="handleLogin"></u-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { login } from '@/api/login'
import CryptoJS from 'crypto-js'

const form = reactive({
  account: 'admin',
  password: '000000'
})

const handleLogin = async () => {
  if (!form.account || !form.password) {
    uni.showToast({
      title: '请输入账号和密码',
      icon: 'none'
    })
    return
  }

  try {
    const response = await login({
      account: form.account,
      password: CryptoJS.MD5(form.password).toString(),
    })

    if (response.code === 0) {
      const { token, userInfo } = response.data
      uni.setStorageSync('token', token)
      uni.setStorageSync('userInfo', userInfo)

      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 2000,
      })

      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/index',
        })
      }, 2000)
    } else {
      uni.showToast({
        title: response.msg || '登录失败',
        icon: 'none',
      })
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    uni.showToast({
      title: '网络错误，请稍后再试',
      icon: 'none',
    })
  }
}
</script>

<style lang="scss">
.login-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx;
  
  .login-form {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 40rpx;
    margin-top: 100rpx;
  }
  
  .login-btn {
    margin-top: 60rpx;
  }
}
</style> 